package com.woniu.admin.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.admin.vo.UserDto;
import com.woniu.admin.pojo.TUser;
import com.woniu.admin.service.UserService;
import com.woniu.admin.vo.AjaxResult;
import com.woniu.admin.vo.TUserVo;
import com.woniu.common.constants.Constants;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/fineUserList")
    public AjaxResult fineUserList(@RequestBody TUserVo userVo) {
        PageHelper.startPage(userVo.getPageNum(), userVo.getPageSize());
        List<TUser> userList = userService.fineUserList(userVo);
        PageInfo<TUser> pageinfo = new PageInfo<>(userList);
        return AjaxResult.success("查询成功!", pageinfo);
    }

    //    登入
//    @PostMapping("/login")
//    public AjaxResult login(@RequestBody TUser user) {
//        TUser tUser = userService.login(user);
//        if (tUser != null) {
//            return AjaxResult.success("200", tUser);
//        } else {
//            return AjaxResult.error("400","用户名或密码错误");
//        }
//    }
    @RequestMapping("/login")
    public AjaxResult login(@RequestBody TUserVo userVo, HttpServletResponse response) throws JsonProcessingException {
        //查询
        UserDto user = userService.login(userVo);

        //存数据到cookie中
        Cookie cookie = new Cookie(Constants.TOKEN, user.getToken());
        cookie.setMaxAge(7 * 24 * 60 * 60);
        cookie.setPath("/");
        response.addCookie(cookie);
        return AjaxResult.success("登录成功", user);
    }

    @PostMapping("/selectOne")
    public AjaxResult selectOne(@RequestBody TUser usernames) {
        List<TUser> tUsers = userService.selectOneUser(usernames);
        System.out.println(tUsers);
        return AjaxResult.success("查询成功!", tUsers);
    }

    @RequestMapping("/delete/{ids}")
    public AjaxResult delete(@PathVariable Integer[] ids) {
        userService.delete(ids);
        return AjaxResult.success("删除成功!");
    }

    @RequestMapping("/add")
    public AjaxResult add(@RequestBody TUser user) {
        userService.add(user);
        return AjaxResult.success("添加成功!");
    }

    @RequestMapping("/update")
    public AjaxResult update(@RequestBody TUser user) {
        userService.update(user);
        return AjaxResult.success("修改成功!");
    }
}
